/* Copyright 2009 Requirements Management System  
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.mags.remas.exception;


import org.apache.derby.impl.jdbc.EmbedSQLException;
import org.mags.exception.common.AbstractExceptionKeyCreator;
import org.mags.exception.common.ExceptionUtils;
import org.springframework.dao.DataIntegrityViolationException;

/**
 * 
 * @author Mario Gaitan
 *
 */
public class DerbyExceptionKeyCreator extends AbstractExceptionKeyCreator {
	@Override
	public String createKey(Throwable exception) {
		EmbedSQLException ex = (EmbedSQLException) ExceptionUtils.findException(exception, EmbedSQLException.class);
		String exceptionName;
		String key = "";
		if(exception instanceof DataIntegrityViolationException) {
			DataIntegrityViolationException diViolationEx = (DataIntegrityViolationException)exception;
			exceptionName = diViolationEx.getClass().getName();
			if(ex.getArguments()!=null&&ex.getArguments().length>0) 
				key = (String)ex.getArguments()[0];
		} else {
			String message = ex.getMessage().toUpperCase();
			if(message.contains("SEE THE NEXT EXCEPTION FOR DETAILS")) {
				if(ex.getCause() instanceof EmbedSQLException) {
					ex = (EmbedSQLException)ex.getCause();
					message = ex.getMessage().toUpperCase();
				}
			}
			exceptionName = ex.getClass().getName();
			if(message.contains("DATABASE")&&message.contains("NOT FOUND")) 
				return "databaseNotFound";
			else if(message.contains("DIRECTORY")&&message.contains("ALREADY EXISTS"))
				return "directoryAlreadyExists";
			else if(message.contains("TABLE/VIEW")&&message.contains("DOES NOT EXIST"))
				return "tableViewDoesNotExists";
			else if(message.contains("CONTAINER")&&message.contains("CANNOT BE OPENED"))
				return "corruptedDatabase";
			else if(message.contains("INVALID AUTHENTICATION"))
				return "invalidAuthentication";
			else {
				//TODO: looking for new specific derby exceptions
			}
		}
		if(!key.equals(""))
			return exceptionName+"."+key;					
		return null;
	}
	@Override
	public boolean canCreate(Throwable exception) {
		Throwable cause = ExceptionUtils.findException(exception, EmbedSQLException.class);
		return cause!=null;
	}
}
